import React, {useEffect} from "react";

import {
    Button, CssBaseline, TextField, FormControlLabel,
    Checkbox, Link, Grid, Box, Typography, Container,
    Paper
} from '@mui/material';
import axios from "axios";
import {useNavigate} from "react-router-dom";

function Copyright(props) {
    return (
        <Typography variant="body2" color="text.secondary" align="center" {...props}>
            {'Copyright © '}
            <Link color="inherit" href="https://chat.cyril.tech/">
                Anonymous Chat Room
            </Link>{' '}
            {new Date().getFullYear()}
            {'.'}
        </Typography>
    );
}

function Login(){
    const getCSRF = () => {
        fetch("/api/csrf", {
            credentials: "same-origin",
        })
            .then((res) => {
                const csrfToken = res.headers.get("X-CSRFToken");
                axios.defaults.headers.common['X-CSRFToken'] = csrfToken
            })
            .catch((err) => {
                console.log(err);
            });
    }
    const getSession = () => {
        getCSRF()
        axios.get("/api/session")
          .then((res) => res.data)
          .then((data) => {
                console.log(data);
                if (data.isAuthenticated) {
                    navigate('/home')
                }
          })
          .catch((err) => {
              console.log(err);
          });
    }

    useEffect(() => {
        getSession()
    }, [])
    const navigate = useNavigate()
    const whoami = () => {
        fetch("/api/whoami/", {
            headers: {
                "Content-Type": "application/json",
            },
            credentials: "same-origin",
        })
            .then((res) => res.json())
            .then((data) => {
                window.alert("You are logged in as: " + data.username);
            })
            .catch((err) => {
                console.log(err);
            });
    }
    const handleSubmit = (event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        // eslint-disable-next-line no-console
        axios.post('/api/login', {
            username: data.get('username'),
            password: data.get('password')
        }).then((res) => {
            if(res.status >= 200 &&res.status <= 299){
                navigate('/')
            } else{
                window.alert(res.data.detail)
            }
        }).catch(err =>{
            console.log(err)
            window.alert(err.response.data.detail)
        })
    };

    return(
        <Container component="main" maxWidth="xs">
            <CssBaseline />
            <Paper elevation={3}>
                <Box sx={{
                margin: '32px 16px',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
            }}>
                <Typography component="h1" variant="h5">
                    Sign in
                </Typography>
                <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
                    <TextField
                        margin="normal"
                        required
                        fullWidth
                        id="username"
                        label="用户名"
                        name="username"
                        autoComplete="username"
                        autoFocus
                        variant="outlined"
                    />
                    <TextField
                        margin="normal"
                        required
                        fullWidth
                        name="password"
                        label="密码"
                        type="password"
                        id="password"
                        autoComplete="current-password"
                        variant="outlined"
                    />
                    <FormControlLabel
                        control={<Checkbox value="remember" color="primary" />}
                        label="Remember me"
                    />
                    <Button
                        type="submit"
                        fullWidth
                        variant="contained"
                        sx={{ mt: 3, mb: 2 }}
                    >
                        Sign In
                    </Button>
                    <Grid container>
                        <Grid item xs>
                            <Link href="#" variant="body2">
                                Forgot password?
                            </Link>
                        </Grid>
                        <Grid item>
                            <Link onClick={e=>{navigate('/signup')}} variant="body2">
                                {"Don't have an account? Sign Up"}
                            </Link>
                        </Grid>
                    </Grid>
                </Box>
            </Box>
            </Paper>
            <Copyright sx={{ mt: 8, mb: 4 }} />
        </Container>
    )
}

export default Login;